Examples of using arrays in Java, from basic to more complex.
Basic Array Initialization and Access
Basic Array Initialization and Access
public class Main{
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5}; // Initialization
System.out.println(myArray[0]); // Accessing an element
}
}
Output
1
Looping Over an Array
Looping Over an Array - Array looping using for loop
public class Main{
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
Output
1
2
3
4
5
Enhanced for Loop (For-Each Loop)
Array with For-Each Loop
public class Main{
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5};
for (int num : myArray) {
System.out.println("Number is :" + num);
}
}
}
Output
Number is :1
Number is :2
Number is :3
Number is :4
Number is :5
Storing Temperatures of a Week
Storing Temperatures of a Week in Java and get the average temperature
public class Main{
public static void main(String[] args) {
double[] temperatures = {20.5, 25.3, 22.7, 26.5, 23.0, 27.8, 24.6};
double total = 0;
for (double temp : temperatures) {
total += temp;
}
double average = total / temperatures.length;
System.out.println("Average temperature of the week: " + average);
}
}
Output
Average temperature of the week: 24.342857142857145
In this example, we’re storing the temperatures of a week in an array and calculating the average temperature.
Storing Student Grades
Storing Student Grades in array and calculating GPA of a student
public class Main{
public static void main(String[] args) {
int[] grades = {85, 90, 95, 92, 88};
int total = 0;
for (int grade : grades) {
total += grade;
}
double gpa = total / grades.length;
System.out.println("Student's GPA: " + gpa);
}
}
Output
Student's GPA: 90.0
In this example, we’re storing the grades of a student in different subjects in an array and calculating the grade point average (GPA).
Storing Product Prices
Storing Product Prices in a array and find the expensive product price
public class Main{
public static void main(String[] args) {
double[] prices = {199.99, 299.99, 249.99, 349.99};
double maxPrice = prices[0];
for (double price : prices) {
if (price > maxPrice) {
maxPrice = price;
}
}
System.out.println("Most expensive product price: " + maxPrice);
}
}
Output
Most expensive product price: 349.99
In this example, we’re storing the prices of different products in an array and finding the most expensive product.
These examples should give you a good understanding of how to use arrays in Java.